package com.kayang.token.service;

import com.kayang.common.core.UserContext;
import com.kayang.common.crypt.Crypt3D;
import com.kayang.common.db.Database;
import com.kayang.common.db.DatabaseFactory;
import com.kayang.nadapt.table.DataRow;
import com.kayang.nadapt.table.DataTable;
import com.kayang.nadapt.util.JsonConvert;
import com.kayang.token.exception.AccessException;
import com.kayang.common.config.RedisUtil;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

@Service
public class JwtService {

    @Autowired
    RedisUtil redisUtil;

    private final String sign = "kayang.toolservice";
    private final String subject = "KYTS";

    private JwtBuilder jwtBuilder = Jwts.builder();
    private JwtParser jwtParser = Jwts.parser();
    public String buildToken(String account, String password) {
        Database db = DatabaseFactory.getDatabase();
        String xsql = "Select id, account, password from skysecuser where account=@1 and (disabled=0 or disabled is null)";
        DataTable dt = db.queryTable(xsql, account);
        if(dt.size() == 0) throw new AccessException();
        if(dt.size() > 0){
            DataRow dataRow = dt.getRows().get(0);
            String dbPwd = dataRow.getString("password");
            int id = dataRow.getInt("id");
            String epwd = Crypt3D.encryptPwd(id, password, false, null);
            if(!dbPwd.equals(epwd)){
             //TODO   throw new AccessException();
            }
        }
        Date startDate = Date.from(LocalDateTime.now().toInstant(ZoneOffset.of("+8")));
        Date expireDate = Date.from(LocalDateTime.now().plusHours(2).toInstant(ZoneOffset.of("+8")));

        UserContext uc = new UserContext();
        uc.setUserID( dt.getRows().get(0).getInt("id"));
        uc.setUserAccount(account);
        String jsonUc = JsonConvert.serializeObject(uc);
        Map<String, Object> map = new HashMap<>();
        map.put("key", jsonUc);
        String id = UUID.randomUUID().toString().toUpperCase().replace("-", "");
        String token = jwtBuilder.setSubject(subject)
                .setIssuedAt(startDate)
                .setId(id)
                .setClaims(map)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS256, sign)
                .compact();

        redisUtil.set(id, token, 60 * 120);// 120分钟
        return id;
    }


    public String checkToken(String id) {
       Object ot = redisUtil.get(id);
       if(ot == null) return null;
        String token = (String) ot;
        jwtParser.setSigningKey(sign);
        //如果token正确(密码，有效期)则正常运行，否则抛出异常
        Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        String jsonUc = body.get("key", String.class);
        return jsonUc;
    }

}
